﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigBreedings
{
    /// <summary>
    /// 种母配种删除Handler
    /// </summary>
    public class DeletePigsBreedingHandler : IRequestHandler<DeletePigsBreedingCommand, Result>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 种母配种
        /// </summary>
        private readonly IBaseRepository<PigsBreeding> pigsBreedingrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DeletePigsBreedingHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigsBreedingrepository"></param>
        /// <param name="logger"></param>
        public DeletePigsBreedingHandler(IMapper mapper, IBaseRepository<PigsBreeding> pigsBreedingrepository, ILogger<DeletePigsBreedingHandler> logger)
        {
            this.mapper = mapper;
            this.pigsBreedingrepository = pigsBreedingrepository;
            _logger = logger;
        }
        /// <summary>
        /// 种母配种删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DeletePigsBreedingCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                var pigsBreeding = await(await pigsBreedingrepository.GetAll()).Where(x => x.PigsBreedingId == request.PigsBreedingId).FirstOrDefaultAsync();
                if (pigsBreeding != null)
                {
                    pigsBreeding.IsDeleted=1;
                    var res = await pigsBreedingrepository.Update(pigsBreeding);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                    }
                }
                result.Msg = "种母配种删除成功";
            }
            catch (Exception ex)
            {
                result.Msg = "种母配种删除失败";
                _logger.LogError("种母配种删除失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
